package com.project.basis.base;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.project.basis.utils.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseVLayoutAdapter<T> extends DelegateAdapter.Adapter<BaseVLayoutAdapter.BaseVLayoutViewHolder> {

    protected OnItemClickListener<T> onItemClickListener;
    private LayoutHelper layoutHelper;
    private int itemViewType;
    protected List<T> list;

    public BaseVLayoutAdapter(LayoutHelper layoutHelper, int itemViewType) {
        this.layoutHelper = layoutHelper;
        this.itemViewType = itemViewType;
        this.list = new ArrayList<>();
    }

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return layoutHelper;
    }

    @Override
    public BaseVLayoutViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(getItemViewId(), parent, false);
        return new BaseVLayoutViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseVLayoutViewHolder holder, int i) {
        onBindViewDataHolder(holder, getItemData(i), i);
    }

    protected abstract int getItemViewId();

    protected abstract void onBindViewDataHolder(BaseVLayoutViewHolder holder, T data, int i);

    @Override
    public int getItemCount() {
        return list.size() == 0 ? layoutHelper.getItemCount() : list.size();
    }

    public List<T> getList() {
        return list;
    }

    public void setOnItemClickListener(OnItemClickListener<T> onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void setList(List<T> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    public void addList(List<T> list) {
        this.list.addAll(list);
        notifyDataSetChanged();
    }

    public T getItemData(int position) {
        if (list.size() > position) {
            return list.get(position);
        }
        return null;
    }

    @Override
    public int getItemViewType(int position) {
        return itemViewType;
    }

    public static class BaseVLayoutViewHolder extends BaseViewHolder {

        public BaseVLayoutViewHolder(View itemView) {
            super(itemView);
        }
    }
}
